package com.bai.msm.controller;

import com.bai.msm.service.MsmService;
import com.bai.utils.R;
import com.bai.utils.RandomUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MsmService msmService;

    //TODO:发送短信
    @ApiOperation("发送短信")
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //从redis里获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        //生成随机值，传递给阿里云进行发送
         code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("param", code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param, phone);
        if (isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.erro().message("短信发生失败");
        }
    }

}
